<template>
  <div class="login">
  <div class="loginTop">主人、请先登录哦</div>
  <img :src="loginBase" id="qrImg" class="loginImg">
  <div id="info"></div>
  </div>
</template>

<script>
import {mapState} from 'vuex'
import {ref} from 'vue'
import { getLoginKey,
          getLoginMessage,
          getLoginStatus,
          createLogin } from '@/request/api/home'
export default {
  setup(){
    let loginBase=ref('')
    return{
    loginBase
    }
  },
  methods:{
    async checkStatus(key) {
        const {data:res} = await getLoginMessage(key) 
        return res
      },
      async getLoginStatus() {
        const res = await getLoginStatus()
        this.$store.commit('updateAccount',res.data)
        if(this.account.data.profile.nickname !== ''){
          this.$store.commit('updateIsLogin',true)
          this.$router.push('/infoUSer')  
        }
      },
      async login() {
        let timer
        this.getLoginStatus()
        const {data:res} = await getLoginKey()
        const key = res.data.unikey
        const {data:res2} = await createLogin(key)
        this.loginBase = res2.data.qrimg
        timer = setInterval(async () => {
          const statusRes = await this.checkStatus(key)
          if (statusRes.code === 800) {
            alert('二维码已过期,请重新获取')
            clearInterval(timer)
          }
          if (statusRes.code === 803) {
            // 这一步会返回cookie
            clearInterval(timer)
            alert('授权登录成功')
            await this.getLoginStatus()
          }
        }, 3000)
      }
  },
  computed:{
    ...mapState(['account']),
  },
  mounted() {
    this.login()
},
}
</script>

<style lang="scss" scoped>
.login{
  width: 100%;
  height: 13.34rem;
  background:url(@/assets/login.jpg) no-repeat;
  background-size: 7.5rem 13.34rem;
  display: flex;
  flex-direction: column;
  align-items: center;

  .loginTop{
    margin-top: 2rem;
    margin-bottom: 2rem;
    font-size: 30px;
    font-weight: 900;
    text-align: center;
    color: rgb(78, 245, 12);
  }
}
</style>
